// Prevents additional console window on Windows in release, DO NOT REMOVE!!
#![cfg_attr(not(debug_assertions), windows_subsystem = "windows")]

use serde::Serialize;
use tauri_app_lib::{database, tray};
// 导入sysInfo模块
mod sysInfo;

#[derive(Debug, Serialize)]
struct OsInfo {
    platform: String,
    arch: String,
    hostname: String,
    family: String,
    os_type: String,
    os_version: String,
    locale: Option<String>,
    exe_extension: String,
}

#[tauri::command]
fn get_os_info() -> Result<OsInfo, String> {
    Ok(OsInfo {
        platform: tauri_plugin_os::platform().to_string(),
        arch: tauri_plugin_os::arch().to_string(),
        hostname: tauri_plugin_os::hostname(),
        family: tauri_plugin_os::family().to_string(),
        os_type: tauri_plugin_os::type_().to_string(),
        os_version: tauri_plugin_os::version().to_string(),
        locale: tauri_plugin_os::locale(),
        exe_extension: tauri_plugin_os::exe_extension().to_string(),
    })
}

#[tokio::main]
async fn main() {
    println!("Starting application...");
    println!("当前目录: {:?}", std::env::current_dir());
    
    // 创建上下文和构建器
    let ctx = tauri::generate_context!();
    tauri::Builder::default()
        // 设置应用初始化
        .setup(|app| {
            // 创建系统托盘
            match tray::create_tray_menu(app) {
                Ok(_) => println!("系统托盘创建成功"),
                Err(e) => println!("系统托盘创建失败: {}", e),
            }

            // 获取应用句柄并克隆，用于数据库初始化
            let app_handle = app.handle().clone();
            
            // 在后台任务中设置数据库
            tokio::spawn(async move {
                match database::setup_database(app_handle).await {
                    Ok(_) => println!("数据库设置成功"),
                    Err(e) => println!("数据库设置失败: {}", e),
                }
            });
            
            Ok(())
        })
        .plugin(tauri_plugin_opener::init())
        .plugin(tauri_plugin_http::init())
        .plugin(tauri_plugin_notification::init())
        .plugin(tauri_plugin_dialog::init())
        .plugin(tauri_plugin_os::init())
        .plugin(tauri_plugin_log::Builder::default().build())
        .plugin(tauri_plugin_sql::Builder::default().build())
        .plugin(tauri_plugin_system_info::init())
        // 设置窗口关闭时，仅隐藏窗口不退出应用
        .on_window_event(|window, event| {
            if let tauri::WindowEvent::CloseRequested { api, .. } = event {
                // 隐藏窗口而不是关闭
                let _ = window.hide();
                // 阻止关闭
                api.prevent_close();
            }
        })
        // 注册命令
        .invoke_handler(tauri::generate_handler![
            get_os_info,
            database::get_users,
            database::add_user,
            database::update_user,
            database::delete_user,
            sysInfo::get_detailed_system_info,
            sysInfo::get_simplified_system_info
        ])
        .run(ctx)
        .expect("error while running tauri application");
}
